const App = {
  mixins: [Save],//配置文件，路径/utils/mixins.js
  data() {
    return {
      category: [],
      northOrganizations: [], // 修改为存储north_organization表的数据
      person: [],
      city1: [],
      qwer: [],
      options: [],
      childDataForm1: [{}],
      is: true,
      cascaderOptions: [], // 新增：级联选择器选项
      dataForm: {
        Activity_Name: '',
        Activity_Type: '大北极联合体', // 设置默认值
        Activity_Content: '',
        Activity_Datetime: '',
        Activity_Location: '',
        Party_Organization_SerialNumber: '', // 存储Organization_SerialNumber
        Creater_SerialNumber: getCookie('user') || '' // 初始化

      },
    };
  },
  mounted() {
    // 使用 getQueryObject 替代 getQueryString
    let ls_URL = window.location.href;
    this.nodeKey = getQueryObject(ls_URL, "nodeKey");
    this.action = getQueryObject(ls_URL, "action");

    if (this.action === 'Modify') {
      this.fetchData();
    }
    this.getNorthOrganizations(); // 修改为获取north_organization数据
  },

  methods: {
    // 获取活动数据
    fetchData() {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        type: "POST",
        data: {
          Data: 'party_organization_activities',
          Condition: `Party_Organization_Activity_SerialNumber='${this.nodeKey}'`
        },
        success: (data) => {
          if (data && data.length > 0) {
            this.dataForm = data[0];
            // 确保活动类型有默认值（如果是新增）
            if (!this.dataForm.Activity_Type) {
              this.dataForm.Activity_Type = '大北极联合体';
            }

            // 编辑模式下设置级联选择器的值
            if (this.action === 'Modify' && this.dataForm.Party_Organization_SerialNumber) {
              this.setCascaderValue();
            }
          }
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },

    // 设置级联选择器值（编辑模式）
    setCascaderValue() {
      const selectedOrg = this.northOrganizations.find(
        org => org.Organization_SerialNumber === this.dataForm.Party_Organization_SerialNumber
      );

      if (selectedOrg) {
        if (selectedOrg.Parent_SerialNumber) {
          // 子节点
          this.cascaderValue = [selectedOrg.Parent_SerialNumber, selectedOrg.Organization_SerialNumber];
        } else {
          // 父节点
          this.cascaderValue = [selectedOrg.Organization_SerialNumber];
        }
      }
    },

    // 提交处理
    handleSubmit() {
      if (this.action === 'Add' && !this.dataForm.Activity_Type) {
        this.dataForm.Activity_Type = '大北极联合体';
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const url = `${mh}/generalBusiness/generalSaveByRequestBody`;

          // 构建请求数据
          const requestData = {
            Data: {
              [this.action === 'Add' ? 'Add' : 'Modify']: {
                party_organization_activities: [{
                  ...this.dataForm,
                  // 修改操作需要包含主键
                  ...(this.action === 'Modify' && {
                    Party_Organization_Activity_SerialNumber: this.nodeKey
                  })
                }]
              }
            }
          };

          // 如果是修改操作，添加条件
          if (this.action === 'Modify') {
            requestData.Condition = `Party_Organization_Activity_SerialNumber='${this.nodeKey}'`;
          }

          $.ajax({
            headers: requestHeaders("JSON"),
            url: url,
            type: "POST",
            data: JSON.stringify(requestData),
            success: (res) => {
              ElMessage.success(this.action === 'Add' ? '添加成功' : '修改成功');
              setTimeout(() => {
                window.location.href = `../north_organization_activities/index.html`;
              }, 1500);
            },
            error: (xhr, status, error) => {
              ElMessage.error(`操作失败: ${xhr.responseText || error}`);
            },
            dataType: "json",
          });
        }
      });
    },
    goBack() {
      window.history.back();
    },

    // 获取north_organization表中的组织数据
    getNorthOrganizations() {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: 'north_organization',
          Condition: "Row_Status='0'" // 根据需要添加条件
        },
        success: (data) => {
          this.northOrganizations = data;
          // 构建级联选择器选项
          this.buildCascaderOptions();
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },

    // 构建级联选择器选项
    buildCascaderOptions() {
      // 找出所有父级组织（Parent_SerialNumber为空的）
      const parentOrgs = this.northOrganizations.filter(
        org => !org.Parent_SerialNumber
      );

      // 构建级联选项
      this.cascaderOptions = parentOrgs.map(parent => {
        // 找出当前父级的所有子组织
        const children = this.northOrganizations.filter(
          org => org.Parent_SerialNumber === parent.Organization_SerialNumber
        );

        return {
          value: parent.Organization_SerialNumber,
          label: parent.Organization_name,
          children: children.map(child => ({
            value: child.Organization_SerialNumber,
            label: child.Organization_name
          }))
        };
      });

      // 编辑模式下设置级联选择器的值
      if (this.action === 'Modify' && this.dataForm.Party_Organization_SerialNumber) {
        this.setCascaderValue();
      }
    },

    // 处理级联选择变化
    handleCascaderChange(value) {
      if (value && value.length > 0) {
        // 取最后一级的值作为选中的组织ID
        this.dataForm.Party_Organization_SerialNumber = value[value.length - 1];
      } else {
        this.dataForm.Party_Organization_SerialNumber = '';
      }
    }

  },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-text-editor', ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.component('yl-cascader', ylCascader);
app.mount("#app");